import { defineStore } from 'pinia';
import { ref, computed } from 'vue';

/**
 * 购物车状态管理
 */

export interface CartItem {
  productId: number;
  productName: string;
  productImage: string;
  price: number;
  quantity: number;
  specs?: string;       // 规格
  tasteOptions?: string; // 口味选项
  categoryId?: number;
}

export const useCartStore = defineStore('cart', () => {
  // 状态
  const items = ref<CartItem[]>([]);
  const merchantId = ref<number>(0);
  const merchantName = ref<string>('');

  // 计算属性
  const totalCount = computed(() => {
    return items.value.reduce((sum, item) => sum + item.quantity, 0);
  });

  const totalPrice = computed(() => {
    return items.value.reduce((sum, item) => sum + item.price * item.quantity, 0);
  });

  // 添加到购物车
  const addItem = (item: CartItem, newMerchantId: number, newMerchantName: string) => {
    // 检查是否同一商家
    if (merchantId.value && merchantId.value !== newMerchantId) {
      uni.showModal({
        title: '提示',
        content: '购物车中已有其他商家的商品,是否清空购物车?',
        success: (res) => {
          if (res.confirm) {
            clearCart();
            merchantId.value = newMerchantId;
            merchantName.value = newMerchantName;
            addItemToCart(item);
          }
        }
      });
      return;
    }

    merchantId.value = newMerchantId;
    merchantName.value = newMerchantName;
    addItemToCart(item);
  };

  // 内部方法:添加商品到购物车
  const addItemToCart = (item: CartItem) => {
    const existingItem = items.value.find(
      i => i.productId === item.productId && i.specs === item.specs
    );

    if (existingItem) {
      existingItem.quantity += item.quantity;
    } else {
      items.value.push({ ...item });
    }

    saveToStorage();
  };

  // 更新商品数量
  const updateQuantity = (productId: number, specs: string | undefined, quantity: number) => {
    const item = items.value.find(
      i => i.productId === productId && i.specs === specs
    );

    if (item) {
      if (quantity <= 0) {
        removeItem(productId, specs);
      } else {
        item.quantity = quantity;
        saveToStorage();
      }
    }
  };

  // 移除商品
  const removeItem = (productId: number, specs: string | undefined) => {
    const index = items.value.findIndex(
      i => i.productId === productId && i.specs === specs
    );

    if (index > -1) {
      items.value.splice(index, 1);
      saveToStorage();
    }

    // 如果购物车为空,清空商家信息
    if (items.value.length === 0) {
      clearCart();
    }
  };

  // 清空购物车
  const clearCart = () => {
    items.value = [];
    merchantId.value = 0;
    merchantName.value = '';
    saveToStorage();
  };

  // 保存到本地存储
  const saveToStorage = () => {
    uni.setStorageSync('cart', {
      items: items.value,
      merchantId: merchantId.value,
      merchantName: merchantName.value
    });
  };

  // 从本地存储加载
  const loadFromStorage = () => {
    const cartData = uni.getStorageSync('cart');
    if (cartData) {
      items.value = cartData.items || [];
      merchantId.value = cartData.merchantId || 0;
      merchantName.value = cartData.merchantName || '';
    }
  };

  return {
    items,
    merchantId,
    merchantName,
    totalCount,
    totalPrice,
    addItem,
    updateQuantity,
    removeItem,
    clearCart,
    loadFromStorage
  };
}, {
  persist: {
    enabled: true,
    strategies: [
      {
        key: 'cart',
        storage: {
          getItem: (key: string) => uni.getStorageSync(key),
          setItem: (key: string, value: string) => uni.setStorageSync(key, value)
        }
      }
    ]
  }
});